import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:linkman/Friend.dart';

class FriendListPage extends StatefulWidget {
  const FriendListPage({Key? key}) : super(key: key);

  @override
  _FriendListPageState createState() => _FriendListPageState();
}

class _FriendListPageState extends State<FriendListPage> {
  List<Friend> friends = [];
  var url = "https://randomuser.me/api/?results=30";

  @override
  void initState() {
    super.initState();
    loadFriendsData();
  }

  loadFriendsData() async {
    HttpClient httpClient = HttpClient();
    HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
    HttpClientResponse response = await request.close();
    var jsonString = await response.transform(utf8.decoder).join();

    setState(() {
      friends = Friend.resolveDataFromResponse(jsonString);
      var size = friends.length;
      print('friends size: $size');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Center(
          child: Text('联系人'),
        ),
      ),
      body: ListView.builder(
          itemCount: friends.length,
          itemBuilder: (BuildContext buildContext, int index) {
            var item = friends.elementAt(index);
            return setListViewData(item);
          }),
    );
  }

  Widget setListViewData(Friend friend) {
    return InkWell(
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Container(
                padding: const EdgeInsets.only(left: 16),
                child: Image.network(
                  friend.avatar,
                  width: 80,
                  height: 80,
                ),
              )),
          Expanded(
              flex: 6,
              child: Container(
                padding: const EdgeInsets.only(left: 2),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(friend.name),
                    Text(
                      friend.email,
                      style:
                          const TextStyle(color: Colors.yellow, fontSize: 12),
                    )
                  ],
                ),
              )),
        ],
      ),
    );
  }
}
